package A一周刷爆LeetCode.B基础提升.A哈希函数与哈希表;

import java.util.HashMap;

/**
 * @author wei.zhao
 * @description: 设计RandomPool结构
 * @date 2022年06月08日 15:53
 */
public class Code01_RandomPool {

    public static class Pool<K> {
        private int size;
        private HashMap<K, Integer> keyIndexMap;
        private HashMap<Integer, K> indexKeyMap;

        public Pool() {
            keyIndexMap = new HashMap<>();
            indexKeyMap = new HashMap<>();
            this.size = 0;
        }

        public void insert(K key) {
            if (!keyIndexMap.containsKey(key)) {
                this.size++;
                keyIndexMap.put(key, this.size);
                indexKeyMap.put(this.size, key);
            }
        }

        public void delete(K key) {
            if (keyIndexMap.containsKey(key)){
                Integer removeIndex = keyIndexMap.get(key);
                keyIndexMap.remove(key);
                K last = indexKeyMap.get(size);
                indexKeyMap.remove(size);
                keyIndexMap.put(last, removeIndex);
                indexKeyMap.put(removeIndex, last);
                size--;
            }
        }

        public K getRandom() {
            int i = (int) Math.random() * this.size + 1;
            return indexKeyMap.get(i);
        }

    }


}
